from jira import JIRA
import jrlib
import os
import openpyxl
import datetime
import sys

gWbMap = dict()


def get_wb_from_file(filename: str):
    global gWbMap
    if filename in gWbMap:
        return gWbMap[filename]
    else:
        if os.path.exists(filename):
            workbook = openpyxl.load_workbook(filename)
        else:
            workbook = openpyxl.Workbook()
        gWbMap[filename] = workbook
        return workbook


def dump_task_to_excel(issues, jrfile="JiraDabase.xlsx", jrsheet="SprintDatabase"):
    jrlib.logprint("dump_task_to_excel() start ...")

    workbook = get_wb_from_file(jrfile)
    if jrsheet in workbook.sheetnames:
        workbook.remove(workbook[jrsheet])

    sheet = workbook.create_sheet(title=jrsheet)
    prevActive = workbook.active
    workbook.active = sheet

    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    sheet.append([f"Generated on {current_time}"])

    headers = [
        "Issue Key",
        "Item ID",
        "Summary",
        "Issue Type",
        "Status",
        "Assignee",
        "Sprint",
        "FB",
        "Time Remaining",
        "Logged Effort",
        "Time All",
        "Original Estimate",
        "Team",
        "Story",
        "StoryStatus",
    ]
    sheet.append(headers)

    data = []
    total_issues = len(issues)
    for idx, issue in enumerate(issues, start=1):
        issue_key = jrlib.getKey(issue)
        summary = jrlib.getSummary(issue)
        item_id = jrlib.getItemId(issue)
        issue_type = jrlib.getIssueType(issue)
        status = jrlib.getStatus(issue)
        assignee = jrlib.getAssignee(issue)
        sprint, _, _ = jrlib.getSprintData(issue)
        sprintfb = jrlib.getSprintFB(sprint)
        time_remaining = jrlib.getTimeRemaining(issue)
        logged_effort = jrlib.getTimeLogged(issue)
        time_all = jrlib.getTimeAll(issue)
        original_estimate = jrlib.getOriginalEstimate(issue)
        team = jrlib.getTeam(issue)
        story, story_status = jrlib.getParentData(issue)

        info = [
            issue_key,
            item_id,
            summary,
            issue_type,
            status,
            assignee,
            sprint,
            sprintfb,
            time_remaining,
            logged_effort,
            time_all,
            original_estimate,
            team,
            story,
            story_status,
        ]
        data.append(info)

        if total_issues >= 10 and idx % (total_issues // 10) == 0:
            jrlib.logprint(
                f"Processed {idx}/{total_issues} issues "
                f"({(idx / total_issues) * 100:.0f}%)"
            )
        elif total_issues > 0 and idx == total_issues:
            jrlib.logprint(f"Processed {idx}/{total_issues} issues " f"(100%)")

    for row in data:
        sheet.append(row)

    workbook.active = prevActive
    workbook.save(jrfile)
    jrlib.logprint("... dump_task_to_excel() finished!")


def dump_epic_to_excel(issues, jrfile="JiraDabase.xlsx", jrsheet="EPICDatabase"):
    jrlib.logprint("dump_epic_to_excel() start ... ")

    workbook = get_wb_from_file(jrfile)
    if jrsheet in workbook.sheetnames:
        workbook.remove(workbook[jrsheet])

    sheet = workbook.create_sheet(title=jrsheet)
    prevActive = workbook.active
    workbook.active = sheet

    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    sheet.append([f"Generated on {current_time}"])

    headers = [
        "Issue Key",
        "Item ID",
        "Summary",
        "Issue Type",
        "Status",
        "Assignee",
        "Start FB",
        "End FB",
        "Time Remaining",
        "Logged Effort",
        "Time All",
        "Original Estimate",
        "Team",
        "Feature",
        "SubFeature",
        "Entity",
    ]
    sheet.append(headers)

    data = []
    total_issues = len(issues)
    for idx, issue in enumerate(issues, start=1):
        issue_key = jrlib.getKey(issue)
        item_id = jrlib.getItemId(issue)
        summary = jrlib.getSummary(issue)
        issue_type = jrlib.getIssueType(issue)
        status = jrlib.getStatus(issue)
        assignee = jrlib.getAssignee(issue)
        start_fb = jrlib.getStartFB(issue)
        end_fb = jrlib.getEndFB(issue)
        time_remaining = jrlib.getTimeRemaining(issue)
        logged_effort = jrlib.getTimeLogged(issue)
        time_all = jrlib.getTimeAll(issue)
        original_estimate = jrlib.getOriginalEstimate(issue)
        team = jrlib.getTeam(issue)
        feature, subfeature, entity = jrlib.getfeatureInfor(item_id)
        info = [
            issue_key,
            item_id,
            summary,
            issue_type,
            status,
            assignee,
            start_fb,
            end_fb,
            time_remaining,
            logged_effort,
            time_all,
            original_estimate,
            team,
            feature,
            subfeature,
            entity,
        ]
        data.append(info)

        if total_issues >= 10 and idx % (total_issues // 10) == 0:
            jrlib.logprint(
                f"Processed {idx}/{total_issues} issues "
                f"({(idx / total_issues) * 100:.0f}%)"
            )
        elif total_issues > 0 and idx == total_issues:
            jrlib.logprint(f"Processed {idx}/{total_issues} issues " f"(100%)")

    for row in data:
        sheet.append(row)

    workbook.active = prevActive
    workbook.save(jrfile)
    jrlib.logprint("... dump_epic_to_excel() finished!")

    return issues, jrfile, jrsheet


def dump_ca_to_excel(issues, jrfile="JiraDabase.xlsx", jrsheet="EPICDatabase"):
    jrlib.logprint(f"dump_epic_to_excel() start ... ")

    workbook = get_wb_from_file(jrfile)
    if jrsheet in workbook.sheetnames:
        workbook.remove(workbook[jrsheet])

    sheet = workbook.create_sheet(title=jrsheet)
    prevActive = workbook.active
    workbook.active = sheet

    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    sheet.append([f"Generated on {current_time}"])

    headers = [
        "Issue Key",
        "Item ID",
        "Summary",
        "Issue Type",
        "Competency Area",
        "Planned System Release",
        "Release Committed FB",
        "Status",
        "Stretch Reason",
        "Delay Reason",
        "Assignee",
        "Start FB",
        "End FB",
        "Time Remaining",
        "Logged Effort",
        "Time All",
        "Original Estimate",
        "Team",
        "Feature",
        "SubFeature",
        "Entity",
        "FOT Leader",
        "Reporter",
    ]
    sheet.append(headers)

    data = []
    total_issues = len(issues)
    for idx, issue in enumerate(issues, start=1):
        issue_key = jrlib.getKey(issue)
        summary = jrlib.getSummary(issue)
        item_id = jrlib.getItemId(issue)
        issue_type = jrlib.getIssueType(issue)
        competency_area = jrlib.getCompetenceArea(issue)
        planned_system_release = jrlib.getPlannedRelease(issue)
        release_committed_fb = jrlib.getReleaseCommittedFB(issue)
        status = jrlib.getStatus(issue)
        stretch_reason = jrlib.getStretchReason(issue)
        delay_reason = jrlib.getDelayReason(issue)
        assignee = jrlib.getAssignee(issue)
        start_fb = jrlib.getStartFB(issue)
        end_fb = jrlib.getEndFB(issue)
        time_remaining = jrlib.getTimeRemaining(issue)
        logged_effort = jrlib.getTimeLogged(issue)
        time_all = jrlib.getTimeAll(issue)
        original_estimate = jrlib.getOriginalEstimate(issue)
        team = jrlib.getTeam(issue)
        feature, subfeature, entity = jrlib.getfeatureInfor(item_id)
        fot_leader = jrlib.getFOTLeader(issue)
        reporter = jrlib.getReporter(issue)
        info = [
            issue_key,
            item_id,
            summary,
            issue_type,
            competency_area,
            planned_system_release,
            release_committed_fb,
            status,
            stretch_reason,
            delay_reason,
            assignee,
            start_fb,
            end_fb,
            time_remaining,
            logged_effort,
            time_all,
            original_estimate,
            team,
            feature,
            subfeature,
            entity,
            fot_leader,
            reporter,
        ]
        data.append(info)

        if total_issues >= 10 and idx % (total_issues // 10) == 0:
            jrlib.logprint(
                f"Processed {idx}/{total_issues} issues "
                f"({(idx / total_issues) * 100:.0f}%)"
            )
        elif total_issues > 0 and idx == total_issues:
            jrlib.logprint(f"Processed {idx}/{total_issues} issues " f"(100%)")

    for row in data:
        sheet.append(row)

    workbook.active = prevActive
    workbook.save(jrfile)
    jrlib.logprint("... dump_ca_to_excel() finished!")


def fetch_store_ca_issues(jira: JIRA, config_file: str = None):
    configs = jrlib.get_ca_configs(config_file)
    for config in configs:
        (
            section,
            section_type,
            section_enable,
            section_jql,
            section_file,
            section_sheet,
        ) = config
        jrlib.logprint(
            f"Section : ({section}),({section_type}),({section_enable}),({section_jql}),({section_file}),({section_sheet}))"
        )
        if not section_enable:
            continue
        issues = jrlib.exectue_jql(jira, section_jql)
        if issues:
            dump_ca_to_excel(issues, section_file, section_sheet)


def fetch_store_epic_issues(jira: JIRA, config_file: str = None):
    configs = jrlib.get_epic_configs(config_file)
    for config in configs:
        (
            section,
            section_type,
            section_enable,
            section_jql,
            section_file,
            section_sheet,
        ) = config
        jrlib.logprint(
            f"Section : ({section}),({section_type}),({section_enable}),({section_jql}),({section_file}),({section_sheet}))"
        )
        if not section_enable:
            continue
        issues = jrlib.exectue_jql(jira, section_jql)
        if issues:
            dump_epic_to_excel(issues, section_file, section_sheet)


def fetch_store_task_issues(jira: JIRA, config_file: str = None):
    configs = jrlib.get_task_configs(config_file)
    for config in configs:
        (
            section,
            section_type,
            section_enable,
            section_jql,
            section_file,
            section_sheet,
        ) = config
        jrlib.logprint(
            f"Section : ({section}),({section_type}),({section_enable}),({section_jql}),({section_file}),({section_sheet}))"
        )
        if not section_enable:
            continue
        issues = jrlib.exectue_jql(jira, section_jql)
        if issues:
            dump_task_to_excel(issues, section_file, section_sheet)


def fetch_store_issues(config_file: str = None):
    jira = jrlib.init_jira_connection(config_file)
    fetch_store_ca_issues(jira, config_file)
    fetch_store_epic_issues(jira, config_file)
    fetch_store_task_issues(jira, config_file)


def main():
    config_file = None
    if len(sys.argv) > 1:
        config_file = sys.argv[1]
    filename = jrlib.get_config_file(config_file)
    fetch_store_issues(filename)


if __name__ == "__main__":
    main()
